<template>
    <div class="teacher-subject-container">
        <el-card class="page-header-card">
            <div class="page-title">我的授课班级</div>
            <el-button type="primary" @click="openHomeworkDialog">作业管理</el-button>
        </el-card>

        <!-- 班级列表 -->
        <el-card class="class-list-card" shadow="hover">
            <el-table :data="classList" border v-loading="loading">
                <el-table-column type="index" label="序号" width="60"></el-table-column>
                <el-table-column prop="name" label="班级名称" width="150"></el-table-column>
                <el-table-column prop="grade" label="年级" width="80">
                    <template #default="scope">
                        {{ scope.row.grade }}年级
                    </template>
                </el-table-column>
                <el-table-column prop="school_num" label="学校编号" width="120"></el-table-column>
                <el-table-column label="课程名称">
                    <template #default="scope">
                        <el-tag v-for="(course, index) in scope.row.courses" :key="index" type="info" size="small"
                            style="margin-right: 5px;">
                            {{ course }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="240">
                    <template #default="scope">
                        <el-button size="small" @click="handleViewStudents(scope.row)">查看学生</el-button>
                        <el-button size="small" type="primary" @click="handleGoToGroupChat(scope.row)">家校群</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 学生列表弹窗 -->
        <el-dialog title="班级学生列表" v-model="studentDialogVisible" width="800px">
            <el-input v-model="studentSearchKeyword" placeholder="搜索学生姓名/学号" clearable
                style="margin-bottom: 15px;"></el-input>

            <el-table :data="filteredStudents" border v-loading="studentLoading">
                <el-table-column type="index" label="序号" width="60"></el-table-column>
                <el-table-column label="头像" width="80">
                    <template #default="scope">
                        <el-avatar :size="40">
                            <img :src="scope.row.avatar || defaultAvatar" />
                        </el-avatar>
                    </template>
                </el-table-column>
                <el-table-column prop="realName" label="姓名" width="120"></el-table-column>
                <el-table-column prop="number" label="学号" width="150"></el-table-column>
                <el-table-column prop="userNum" label="监护人"></el-table-column>
                <el-table-column prop="idCard" label="身份证号" width="200"></el-table-column>
                <el-table-column prop="schoolNum" label="学校编号" width="120"></el-table-column>
                <el-table-column prop="status" label="状态">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                            {{ scope.row.status === 1 ? '正常' : '禁用' }}
                        </el-tag>
                    </template>
                </el-table-column>
            </el-table>

            <template #footer>
                <el-button @click="studentDialogVisible = false">关闭</el-button>
            </template>
        </el-dialog>

        <!-- 作业管理弹窗 -->
        <el-dialog v-model="homeworkDialogVisible" title="作业管理" :width="isMobile ? '90%' : '1000px'"
            :close-on-click-modal="false">
            <el-tabs v-model="activeTab" type="card">
                <!-- 发布新作业 -->
                <el-tab-pane label="发布新作业" name="publish">
                    <el-form ref="homeworkFormRef" :model="homeworkForm" label-width="100px" class="homework-form">
                        <el-form-item label="作业标题" prop="title"
                            :rules="[{ required: true, message: '请输入作业标题', trigger: 'blur' }]">
                            <el-input v-model="homeworkForm.title" maxlength="100" placeholder="请输入作业标题"></el-input>
                        </el-form-item>

                        <el-form-item label="所属班级" prop="classId"
                            :rules="[{ required: true, message: '请选择班级', trigger: 'change' }]">
                            <el-select v-model="homeworkForm.classId" placeholder="请选择班级">
                                <el-option v-for="cls in classList" :key="cls.id" :label="cls.name"
                                    :value="cls.id"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="科目" prop="subject">
                            <el-select v-model="homeworkForm.subject" placeholder="请选择科目">
                                <el-option label="语文" value="chinese"></el-option>
                                <el-option label="数学" value="math"></el-option>
                                <el-option label="英语" value="english"></el-option>
                                <el-option label="科学" value="science"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="布置时间" prop="assignDate"
                            :rules="[{ required: true, message: '请选择布置时间', trigger: 'change' }]">
                            <el-date-picker v-model="homeworkForm.assignDate" type="date"
                                placeholder="选择日期"></el-date-picker>
                        </el-form-item>

                        <el-form-item label="截止时间" prop="dueDate"
                            :rules="[{ required: true, message: '请选择截止时间', trigger: 'change' }]">
                            <el-date-picker v-model="homeworkForm.dueDate" type="date"
                                placeholder="选择日期"></el-date-picker>
                        </el-form-item>

                        <el-form-item label="作业总分" prop="totalScore">
                            <el-input v-model="homeworkForm.totalScore" type="number" placeholder="默认100分"></el-input>
                        </el-form-item>

                        <el-form-item label="作业要求" prop="homeworkRequire">
                            <el-input v-model="homeworkForm.homeworkRequire" type="textarea" rows="3"
                                placeholder="请输入作业要求"></el-input>
                        </el-form-item>

                        <el-form-item label="作业内容" prop="content"
                            :rules="[{ required: true, message: '请输入作业内容', trigger: 'blur' }]">
                            <el-input v-model="homeworkForm.content" type="textarea" rows="5"
                                placeholder="请输入作业详细内容"></el-input>
                        </el-form-item>

                        <el-form-item label="附件上传">
                            <el-upload class="upload-demo" :file-list="uploadFiles" :limit="5" :auto-upload="false"
                                :on-change="handleFileChange" :on-remove="handleFileRemove" :on-exceed="handleExceed"
                                :before-upload="beforeUpload" multiple>
                                <el-button type="primary">选择文件</el-button>
                                <template #tip>
                                    <div class="el-upload__tip">
                                        支持上传 doc, docx, pdf, jpg, png 格式文件，单个文件不超过10MB，最多5个
                                    </div>
                                </template>
                            </el-upload>

                            <div v-if="uploadProgress.visible" class="upload-progress">
                                <el-progress :percentage="uploadProgress.percentage" :status="uploadProgress.status"
                                    :text-inside="true" :stroke-width="20" />
                                <div class="progress-info">{{ uploadProgress.info }}</div>
                            </div>
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" @click="submitHomework" :loading="submitting">发布作业</el-button>
                            <el-button @click="resetHomeworkForm">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>

                <!-- 我的作业列表 -->
                <el-tab-pane label="我的作业" name="list">
                    <el-input v-model="homeworkSearch" placeholder="搜索作业标题" clearable
                        style="margin-bottom: 15px;"></el-input>

                    <el-table :data="filteredHomeworks" border>
                        <el-table-column type="index" label="序号" width="60"></el-table-column>
                        <el-table-column prop="title" label="作业名称"></el-table-column>
                        <el-table-column prop="subject" label="科目" :formatter="formatSubject"></el-table-column>
                        <el-table-column prop="assignDate" label="布置时间"></el-table-column>
                        <el-table-column prop="dueDate" label="截止时间"></el-table-column>
                        <el-table-column prop="totalScore" label="总分"></el-table-column>
                        <el-table-column label="操作" width="200">
                            <template #default="scope">
                                <el-button size="small" @click="viewHomeworkDetails(scope.row.id)">查看附件</el-button>
                                <el-button size="small" type="primary"
                                    @click="viewSubmissions(scope.row.id)">查看提交</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <div class="pagination" v-if="teacherHomeworks && teacherHomeworks.length > 0">
                        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                            :current-page="currentPage" :page-sizes="[5, 10, 20]" :page-size="pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="teacherHomeworks.length"></el-pagination>
                    </div>
                </el-tab-pane>

                <!-- 作业提交详情 -->
                <el-tab-pane label="提交详情" name="submissions" v-if="currentProblemId">
                    <el-table :data="homeworkResults" border>
                        <el-table-column type="index" label="序号" width="60"></el-table-column>
                        <el-table-column prop="studentNum" label="学生学号"></el-table-column>
                        <el-table-column prop="studentName" label="学生姓名"></el-table-column>
                        <el-table-column prop="submitTime" label="提交时间"></el-table-column>
                        <el-table-column label="结果">
                            <template #default="scope">
                                <el-button size="small" @click="showSubmissionContent(scope.row)">查看结果</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="score" label="得分">
                            <template #default="scope">
                                <el-input v-model="scope.row.score" type="number" size="small"
                                    :max="currentHomework.totalScore" @change="handleScoreChange(scope.row)"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="teacherComment" label="评语">
                            <template #default="scope">
                                <el-input v-model="scope.row.teacherComment" type="textarea" size="small" rows="2"
                                    @change="handleCommentChange(scope.row)"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="160">
                            <template #default="scope">
                                <div class="operation-btn-group">
                                    <el-button size="small" type="primary" @click="viewResultFiles(scope.row.id)">查看附件</el-button>
                                    <el-button size="small" type="success" @click="saveScoreAndComment(scope.row)"
                                        :disabled="!scope.row.score">
                                        保存
                                    </el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-dialog>

        <!-- 作业附件查看弹窗 -->
        <el-dialog v-model="fileDialogVisible" title="附件列表" width="500px">
            <div v-if="currentFiles.length > 0" class="file-dialog-list">
                <div v-for="file in currentFiles" :key="file.id" class="file-list-item">
                    <el-link :href="file.filePath" target="_blank" style="flex: 1;">
                        <el-icon>
                            <Document />
                        </el-icon>
                        {{ file.fileName }}
                    </el-link>
                    <div>
                        <span class="file-size-text">{{ formatFileSize(file.fileSize) }}</span>
                    </div>
                </div>
            </div>
            <div v-else style="padding: 20px 0; text-align: center; color: #999;">
                无附件
            </div>
        </el-dialog>

        <!-- 提交结果内容弹窗 -->
        <el-dialog v-model="submissionContentVisible" title="提交结果" width="600px">
            <div class="submission-content">
                <p v-if="!currentSubmissionContent" style="text-align: center; color: #999;">无提交内容</p>
                <div v-else v-html="currentSubmissionContent"></div>
            </div>
            <template #footer>
                <el-button @click="submissionContentVisible = false">关闭</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
    import {
        ref,
        computed,
        onMounted,
        reactive,
        watch
    } from 'vue';
    import {
        useRouter
    } from 'vue-router';
    import {
        ElMessage
    } from 'element-plus';
    import {
        Document
    } from '@element-plus/icons-vue';

    import {
        getClassByUserNum,
        getStudentsByClassId
    } from '../../../../api/user-teacher-subject/user-teacher-subject.js';
    import {
        useLoginStore
    } from '../../../../stores/index.js';
    import {
        insertHomeworkProblem,
        getHomeworkProblemByUserNum,
        getHomeworkResultByProblemId,
        updateHomeworkScoreAndTCommentAndCorrectTime,
        getHomeworkResultFileByResultId,
        getHomeworkProblemFileByProblemId
    } from '../../../../api/homework/homework.js'

    const router = useRouter();

    // 状态管理
    const loading = ref(false);
    const studentLoading = ref(false);
    const classList = ref([]);
    const currentClass = ref(null);
    const studentList = ref([]);
    const studentDialogVisible = ref(false);
    const studentSearchKeyword = ref('');
    const defaultAvatar = 'https://picsum.photos/seed/student/100/100';

    // 弹窗控制
    const homeworkDialogVisible = ref(false);
    const fileDialogVisible = ref(false);
    const submissionContentVisible = ref(false); // 提交内容弹窗控制
    const isMobile = ref(window.innerWidth <= 768);

    // 标签页控制
    const activeTab = ref('publish');
    const currentProblemId = ref('');
    const currentHomework = ref({});
    const currentFiles = ref([]);
    const currentSubmissionContent = ref(''); // 当前查看的提交内容

    const homeworkFormRef = ref(null)
    // 表单数据
    const homeworkForm = reactive({
        title: '',
        classId: '',
        subject: '',
        assignDate: new Date(),
        dueDate: new Date(),
        totalScore: 100,
        homeworkRequire: '',
        content: ''
    });

    // 上传文件
    const uploadFiles = ref([]);
    const submitting = ref(false);

    // 添加上传进度状态
    const uploadProgress = reactive({
        visible: false,
        percentage: 0,
        status: 'success',
        info: ''
    });

    // 作业列表数据
    const teacherHomeworks = ref([]);
    const filteredHomeworks = ref([]);
    const homeworkSearch = ref('');
    const currentPage = ref(1);
    const pageSize = ref(10);

    // 作业提交结果
    const homeworkResults = ref([]);

    // 教师ID
    const userNum = useLoginStore().user.number;

    // 打开作业管理弹窗
    const openHomeworkDialog = () => {
        homeworkDialogVisible.value = true;
        fetchTeacherHomeworks()
    };

    // 获取教师的作业列表
    const fetchTeacherHomeworks = async () => {
        try {
            console.log(userNum);
            const response = await getHomeworkProblemByUserNum(userNum);
            console.log(response);
            teacherHomeworks.value = response || [];
            filterHomeworks();
        } catch (error) {
            ElMessage.error('获取作业列表失败');
            console.error(error);
            teacherHomeworks.value = [];
        }
    };

    // 处理文件选择
    const handleFileChange = (file, fileList) => {
        uploadFiles.value = fileList;
    };

    // 处理文件移除
    const handleFileRemove = (file, fileList) => {
        uploadFiles.value = fileList;
    };

    // 文件超出限制处理
    const handleExceed = (files, fileList) => {
        ElMessage.warning(`最多只能上传5个文件，当前选择了 ${files.length} 个文件，共 ${files.length + fileList.length} 个文件`);
    };

    // 上传前验证
    const beforeUpload = (file) => {
        const isLt10M = file.size / 1024 / 1024 < 10;
        if (!isLt10M) {
            ElMessage.error('文件大小不能超过10MB');
            return false;
        }
        return true;
    };

    // 筛选作业
    const filterHomeworks = () => {
        const homeworks = Array.isArray(teacherHomeworks.value) ? teacherHomeworks.value : [];
        filteredHomeworks.value = homeworks.filter(homework =>
            homework && homework.title && homework.title.includes(homeworkSearch.value)
        );
    };

    // 监听搜索框变化
    watch(homeworkSearch, filterHomeworks);

    // 提交作业
    const submitHomework = async () => {
        try {
            if (!homeworkForm.title || !homeworkForm.classId) {
                ElMessage.error('请填写必填字段');
                return;
            }

            submitting.value = true;

            uploadProgress.visible = true;
            uploadProgress.percentage = 0;
            uploadProgress.status = 'success';
            uploadProgress.info = '开始上传...';

            const formatDateToLocalDate = (date) => {
                if (!date) return '';
                const d = new Date(date);
                const year = d.getFullYear();
                const month = String(d.getMonth() + 1).padStart(2, '0');
                const day = String(d.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            };

            const problemData = {
                userNum: userNum,
                classId: homeworkForm.classId,
                subject: homeworkForm.subject,
                title: homeworkForm.title,
                homeworkRequire: homeworkForm.homeworkRequire,
                content: homeworkForm.content,
                assignDate: formatDateToLocalDate(homeworkForm.assignDate),
                dueDate: formatDateToLocalDate(homeworkForm.dueDate),
                totalScore: homeworkForm.totalScore
            };

            const files = uploadFiles.value.map(file => file.raw);

            const response = await insertHomeworkProblem(problemData, files);

            uploadProgress.percentage = 100;
            uploadProgress.info = '上传完成';

            if (response == 1) {
                ElMessage.success('作业发布成功');
                resetHomeworkForm();
                fetchTeacherHomeworks();
                activeTab.value = 'list';
            } else {
                ElMessage.error(response?.message || '作业发布失败');
            }
        } catch (error) {
            uploadProgress.status = 'exception';
            uploadProgress.info = '上传失败';
            ElMessage.error('提交失败，请重试');
            console.error(error);
        } finally {
            submitting.value = false;
            setTimeout(() => {
                uploadProgress.visible = false;
            }, 2000);
        }
    };

    // 重置表单
    const resetHomeworkForm = () => {
        homeworkForm.title = '';
        homeworkForm.classId = '';
        homeworkForm.subject = '';
        homeworkForm.assignDate = new Date();
        homeworkForm.dueDate = new Date();
        homeworkForm.totalScore = 100;
        homeworkForm.homeworkRequire = '';
        homeworkForm.content = '';
        uploadFiles.value = [];
    };

    // 查看作业详情
    const viewHomeworkDetails = async (problemId) => {
        try {
            const homework = teacherHomeworks.value.find(item => item.id === problemId);
            if (homework) {
                currentHomework.value = homework;
                const fileResponse = await getHomeworkProblemFileByProblemId(problemId);
                currentFiles.value = fileResponse || [];
                fileDialogVisible.value = true;
            }
        } catch (error) {
            ElMessage.error('获取作业详情失败');
            console.error(error);
        }
    };

    // 查看提交情况
    const viewSubmissions = async (problemId) => {
        try {
            currentProblemId.value = problemId;
            currentHomework.value = teacherHomeworks.value.find(item => item.id === problemId) || {};
            const response = await getHomeworkResultByProblemId(problemId);
            homeworkResults.value = (response || []).map(item => ({
                ...item,
                studentName: item.studentName || `学生${item.studentNum}`,
                hasFile: item.hasFile || false
            }));
            activeTab.value = 'submissions';
        } catch (error) {
            ElMessage.error('获取提交列表失败');
            console.error(error);
        }
    };

    // 查看提交内容
    const showSubmissionContent = (row) => {
        currentSubmissionContent.value = row.submissionContent || '';
        submissionContentVisible.value = true;
    };

    // 查看提交附件
    const viewResultFiles = async (resultId) => {
        try {
            const response = await getHomeworkResultFileByResultId(resultId);
            currentFiles.value = response || [];
            fileDialogVisible.value = true;
        } catch (error) {
            ElMessage.error('获取附件列表失败');
            console.error(error);
        }
    };

    // 保存分数和评语
    const saveScoreAndComment = async (row) => {
        try {
            const response = await updateHomeworkScoreAndTCommentAndCorrectTime(
                row.score,
                row.teacherComment,
                row.id
            );

            if (response != null) {
                ElMessage.success('保存成功');
            } else {
                ElMessage.error('保存失败');
            }
        } catch (error) {
            ElMessage.error('操作失败，请重试');
            console.error(error);
        }
    };

    // 格式化科目名称
    const formatSubject = (row) => {
        const subjectMap = {
            'chinese': '语文',
            'math': '数学',
            'english': '英语',
            'science': '科学'
        };
        return subjectMap[row.subject] || row.subject;
    };

    // 格式化文件大小
    const formatFileSize = (size) => {
        if (!size) return '0B';
        const units = ['B', 'KB', 'MB', 'GB'];
        let unitIndex = 0;
        while (size >= 1024 && unitIndex < units.length - 1) {
            size /= 1024;
            unitIndex++;
        }
        return `${size.toFixed(2)}${units[unitIndex]}`;
    };

    // 分页处理
    const handleSizeChange = (val) => {
        pageSize.value = val;
        currentPage.value = 1;
    };

    const handleCurrentChange = (val) => {
        currentPage.value = val;
    };

    // 监听窗口大小变化
    const handleResize = () => {
        isMobile.value = window.innerWidth <= 768;
    };

    window.addEventListener('resize', handleResize);

    // 过滤学生列表
    const filteredStudents = computed(() => {
        if (!studentSearchKeyword.value) return studentList.value;
        const keyword = studentSearchKeyword.value.toLowerCase();
        return studentList.value.filter(student =>
            (student.real_name && student.real_name.toLowerCase().includes(keyword)) ||
            (student.number && student.number.toLowerCase().includes(keyword))
        );
    });

    // 获取教师授课班级
    const fetchTeacherClasses = async () => {
        try {
            loading.value = true;
            const loginStore = useLoginStore();
            const userNum = loginStore.user.number;

            if (!userNum) {
                ElMessage.error('未获取到用户信息，请重新登录');
                return;
            }

            const result = await getClassByUserNum(userNum);
            const rawClasses = result || [];

            const classMap = {};
            rawClasses.forEach(item => {
                const classId = item.class_id;
                if (!classMap[classId]) {
                    classMap[classId] = {
                        id: classId,
                        name: item.class_name,
                        grade: item.grade,
                        school_num: item.school_num,
                        courses: []
                    };
                }
                classMap[classId].courses.push(item.course_name);
            });

            classList.value = Object.values(classMap);
        } catch (error) {
            ElMessage.error('获取班级列表失败：' + (error.message || '网络错误'));
        } finally {
            loading.value = false;
        }
    };

    // 获取班级学生
    const fetchClassStudents = async (classId) => {
        try {
            studentLoading.value = true;
            const result = await getStudentsByClassId(classId);
            studentList.value = result || [];
        } catch (error) {
            ElMessage.error('获取学生列表失败：' + (error.message || '网络错误'));
        } finally {
            studentLoading.value = false;
        }
    };

    // 查看学生
    const handleViewStudents = (cls) => {
        currentClass.value = cls;
        studentDialogVisible.value = true;
        fetchClassStudents(cls.id);
    };

    // 前往家校群
    const handleGoToGroupChat = (cls) => {
        router.push(`/user/teacher/groupChat/${cls.id}`);
    };

    // 页面加载时获取数据
    onMounted(() => {
        fetchTeacherClasses();
    });
</script>

<style scoped>
    .teacher-subject-container {
        padding: 20px;
        max-width: 1200px;
        margin: 0 auto;
    }

    .page-header-card {
        margin-bottom: 20px;
        border: none;
        background-color: #f5f7fa;
    }

    .page-title {
        font-size: 20px;
        font-weight: 600;
        color: #1f2329;
        padding: 15px 0;
    }

    .class-list-card {
        margin-bottom: 20px;
    }

    ::v-deep .el-table th {
        background-color: #f7f8fa;
    }

    .homework-form {
        margin-top: 15px;
    }

    .pagination {
        margin-top: 15px;
        text-align: right;
    }

    .upload-demo {
        margin-top: 10px;
    }

    .file-dialog-list {
        padding: 10px 0;
    }

    .file-list-item {
        display: flex;
        align-items: center;
        padding: 8px 0;
        border-bottom: 1px solid #f2f2f2;
    }

    .file-dialog-list .el-icon {
        margin-right: 8px;
        color: #409eff;
    }

    .file-size-text {
        margin-left: auto;
        color: #666;
        font-size: 12px;
    }

    .submission-content {
        max-height: 400px;
        overflow-y: auto;
        line-height: 1.6;
        padding: 10px 0;
    }

    .operation-btn-group {
        display: flex;
        gap: 5px;
    }
</style>